package src.leetcode.hot.mid_0057;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class insert {
    public static void main(String[] args) {
        Solution solution = new Solution();
        int[][] intervals = {{1, 3}, {6, 9}};
        int[] newInterval = {2, 5};
        System.out.println(Arrays.deepToString(solution.insert(intervals, newInterval)));
    }
}

class Solution {
    public int[][] insert(int[][] intervals, int[] newInterval) {
        List<int[]> list = new ArrayList<>();
        boolean flag = false;
        for (int i = 0; i < intervals.length; ) {
            if (newInterval[0] > intervals[i][1] || flag == true) {
                list.add(intervals[i]);
                i++;
            } else if (newInterval[1] < intervals[i][0] && flag == false) {
                list.add(newInterval);
                flag = true;
            } else {
                newInterval[0] = Math.min(newInterval[0], intervals[i][0]);
                newInterval[1] = Math.max(newInterval[1], intervals[i][1]);
                i++;
            }
        }
        if (list.get(list.size() - 1)[1] < newInterval[0]) list.add(newInterval);
        return list.toArray(new int[list.size()][]);
    }
}